#include "NetworkPacket.h"

std::string NetworkPacket::str() const{
	std::stringstream payload;
	payload << *this;
	return payload.str();
}

/*!
 * Defines an output << operator for NetworkPacket. The output will include the type of the packet, the destination, the source and the data.
 * \param[in] out	The output stream in which the output will go to (usualy cout)
 * \param[in] p		The network packet to read from
 * \return An output description of the network packet p
*/
std::ostream& operator<<(std::ostream& out, const NetworkPacket& p){
	out << "<t>" << (int)p.type 
			<< "<d>" << (int)p.destination 
			<< "<s>" << (int)p.source 
			<< "<p>" << (int)p.data << "</>";
	return out;
}

/*!
 * Parses the char string into a NetworkPacket
 * \param[in] input		The intput string to be parsed for NetworkPacket
 */
NetworkPacket::NetworkPacket(const char* input){
	DEBUG("Creating packet from input: " << input); 
	
	//offset required to skip the packet header created by the tos printf
	input += 8;
	DEBUG("After offset: " << input);
	type = dataFromChar('t', input);
	destination = dataFromChar('d', input);
	source = dataFromChar('s', input);
	data = dataFromChar('p', input);
}

/*!
 * Parses the data out of an input string, of the type specified by c
 * \param[in] c The type of data
 * \param[in] input The data to be parsed
 * \return The result of the parsing, 0 if data not found.
 */
int NetworkPacket::dataFromChar(char c, const char* input){
	char indicator[4] = {'<', c, '>', '\0'};
	int tagLength = 3;
	char* start = strstr(input, indicator);
	
	if(start == '\0'){
		return 0;
	}
	
	const char* end = strstr(start+1, "<");
	
	if(end == '\0'){
		return 0;
	}
	
	char* temp = (char*)malloc((end-start - tagLength) * sizeof(char) + 1);
	strncpy(temp, start+tagLength, end-start);
	
	//Add termination character
	temp[(end-start - tagLength) * sizeof(char)] = '\0';
	
	int result = atoi(temp);
	free(temp);
	return result;
}
